package com.vf.common.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.BasicCredentials;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.VoidResult;
import com.aliyuncs.exceptions.ClientException;
import com.vf.common.properties.AliyunOssProperties;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.InputStream;


@Slf4j
@Component
public class OssClient{

    @Getter
    @Autowired
    private AliyunOssProperties aliyunOssProperties;
    private OSS client;

    @PostConstruct
    private void createClient() throws ClientException {
        assert aliyunOssProperties != null;
        String endpoint = aliyunOssProperties.getEndpoint();
        // 替换为您的 Bucket 区域
        String bucketName = aliyunOssProperties.getBucketName();
        String region = aliyunOssProperties.getRegion();
        String accessKeyId = aliyunOssProperties.getAccessKeyId();
        String accessKeySecret = aliyunOssProperties.getAccessKeySecret();
        BasicCredentials basicCredentials = new BasicCredentials(accessKeyId, accessKeySecret, null);
        // 创建 OSSClient 实例
        this.client = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(new DefaultCredentialProvider(basicCredentials))
                .region(region)
                .build();
        if (!this.client.doesBucketExist(bucketName)) {
            this.client.createBucket(bucketName);
        }
    }

    public PutObjectResult upload(String objectName, InputStream is){
        return upload(aliyunOssProperties.getBucketName(),objectName,is);
    }

    public PutObjectResult upload(String bucketName, String objectName, InputStream is){
        return this.client.putObject(bucketName,objectName,is);
    }

    public OSSObject download(String objectName){
        return download(aliyunOssProperties.getBucketName(), objectName);
    }

    public OSSObject download(String bucketName, String objectName){
        return this.client.getObject(bucketName,objectName);
    }

    public VoidResult delete(String objectName){
        return delete(aliyunOssProperties.getBucketName(),objectName);
    }

    public VoidResult delete(String bucketName, String objectName){
        return this.client.deleteObject(bucketName, objectName);
    }

}
